<?php

namespace app\common\repositories\user;


use app\common\dao\BaseDao;
use app\common\dao\user\UserIntegralBillDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\store\order\PresellOrderRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\product\ProductRepository;
use crmeb\jobs\SendSmsJob;
use think\facade\Db;
use think\facade\Queue;
use think\Model;

class UserIntegralBillRepository extends BaseRepository
{
    /**
     * @var UserIntegralBillDao
     */
    protected $dao;

    const TYPE_INFO = [
        'integral/cancel' => '退回积分',
        'integral/lock' => '下单赠送积分',
        'integral/refund' => '订单退款',
        'integral/refund_lock' => '扣除赠送积分',
        'integral/sign_integral' => '签到赠送积分',
        'integral/spread' => '邀请好友',
        'integral/sys_dec' => '系统减少积分',
        'integral/sys_inc' => '系统增加积分',
        'integral/timeout' => '积分过期',
        'mer_integral/deduction' => '积分抵扣',
        'mer_integral/refund' => '订单退款',

        'integral/buy_product' => '下单赠送积分',
        'integral/buy_seckill_product' => '购买秒杀商品赠送积分',
        'integral/evaluate' => '评价赠送积分',
    ];

    /**
     * UserIntegralRepository constructor.
     * @param UserIntegralBillDao $dao
     */
    public function __construct(UserIntegralBillDao $dao)
    {
        $this->dao = $dao;
    }

    public function userList($where, $uid, $page, $limit)
    {
        $where['uid'] = $uid;
        $query = $this->dao->search($where)->order('create_time DESC');
        $count = $query->count();
        $list = $query->setOption('field', [])->field('bill_id,pm,title,number,balance,mark,create_time,status')->page($page, $limit)->select();
        return compact('count', 'list');
    }

    public function month(array $where)
    {
        $group = $this->dao->search($where)->field('FROM_UNIXTIME(unix_timestamp(create_time),"%Y-%m") as time')
            ->order('time DESC')->group('time')->select();
        $ret = [];
        foreach ($group as $k => $item){
            $ret[$k]['month'] = $item['time'];
            $query = $this->dao->getSearch($where)->field('title,number,create_time')->whereMonth('create_time',$item['time']);
            $ret[$k]['list'] = $query->order('create_time DESC')->select();
        }
        return $ret;
    }

    public function getList($where, $page, $limit)
    {
        $query = $this->dao->searchJoin($where)->order('a.create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact('count', 'list');
    }

    public function getLst($where, $page, $limit)
    {
        $query = $this->dao->search($where)->order('create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact('count', 'list');
    }

    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param int $pm
     * @param array $data
     * @return BaseDao|Model
     * @author: fupeng
     * @day: 2024/3/21
     */
    public function bill(int $uid, string $category, string $type, int $pm, array $data)
    {
        $data['category'] = $category;
        $data['type'] = $type;
        $data['uid'] = $uid;
        $data['pm'] = $pm;
        $bill = $this->dao->create($data);
        if($category == 'now_money'){
            Queue::push(SendSmsJob::class,['tempId' => 'USER_BALANCE_CHANGE','id' => $bill->bill_id]);
        }
        return $bill;
    }

    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param array $data
     * @return BaseDao|Model
     * @author: fupeng
     * @day: 2024/3/21
     */
    public function incBill(int $uid, string $category, string $type, array $data)
    {
        return $this->bill($uid, $category, $type, 1, $data);
    }

    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param array $data
     * @return BaseDao|Model
     * @author: fupeng
     * @day: 2024/3/21
     */
    public function decBill(int $uid, string $category, string $type, array $data)
    {
        return $this->bill($uid, $category, $type, 0, $data);
    }

    public function type()
    {
        $data = [];
        foreach (self::TYPE_INFO as $type => $title) {
            $data[] = compact('type', 'title');
        }
        return $data;
    }

    /**
     * TODO 积分日志头部统计
     * @param $merId
     * @return array[]
     * @author: fupeng
     * @day: 2024/3/21
     */
    public function getStat($merId = 0)
    {
        if($merId){
            $isusd = app()->make(ProductRepository::class)->getSearch(['mer_id' => $merId])->sum('integral_total');
            $refund = $this->dao->search(['category' => 'mer_integral','type' => 'refund','mer_id' => $merId])->sum('number');
            $numb = app()->make(ProductRepository::class)->getSearch(['mer_id' => $merId])->sum('integral_price_total');
            return [
                [
                    'className' => 'el-icon-s-cooperation',
                    'count' => $isusd,
                    'field' => '个',
                    'name' => '已使用积分（分）'
                ],
                [
                    'className' => 'el-icon-edit',
                    'count' => $refund,
                    'field' => '次',
                    'name' => '退款订单返回积分（分）'
                ],
                [
                    'className' => 'el-icon-edit',
                    'count' => $numb,
                    'field' => '次',
                    'name' => '积分抵扣金额（元）'
                ],
            ];
        }
        // 总积分
        $integral = app()->make(UserRepository::class)->search(['status' => 1])->sum('integral');
        // 客户签到次数
        $sign = app()->make(UserSignRepository::class)->getSearch([])->count('*');
        // 签到送出积分
        $sign_integral = $this->dao->search(['type' => 'sign_integral'])->sum('number');
        // 使用积分
        $isusd  = $this->dao->search(['category' => 'integral','type' => 'deduction'])->sum('number');
        $refund = $this->dao->search(['category' => 'mer_integral','type' => 'refund'])->sum('number');
        $order = $isusd - $refund;

        // 下单赠送积分
        $order_integral1 = $this->dao->search(['category' => 'integral','type' => 'lock'])->sum('number');
        $order_integral2 = $this->dao->search(['category' => 'integral','type' => 'refund_lock'])->sum('number');
        $order_integral = $order_integral1 - $order_integral2;
        $order_integral = $order_integral < 0 ? 0 : $order_integral;
        // 冻结积分
        $freeze_integral = $this->dao->lockIntegral();

        return [
            [
                'className' => 'el-icon-s-cooperation',
                'count' => $integral,
                'field' => '个',
                'name' => '总积分'
            ],
            [
                'className' => 'el-icon-edit',
                'count' => $sign,
                'field' => '次',
                'name' => '客户签到次数'
            ],
            [
                'className' => 'el-icon-s-goods',
                'count' => $sign_integral ,
                'field' => '个',
                'name' => '签到送出积分'
            ],
            [
                'className' => 'el-icon-s-order',
                'count' => $order,
                'field' => '个',
                'name' => '使用积分'
            ],
            [
                'className' => 'el-icon-present',
                'count' => $order_integral,
                'field' => '个',
                'name' => '下单赠送积分'
            ],
            [
                'className' => 'el-icon-warning',
                'count' => $freeze_integral,
                'field' => '',
                'name' => '冻结积分'
            ],
        ];
    }

    public function taskEvaluateIntegral($data,$order_id){
        $config = userIntegralConfig('evaluate');
        if($config['status'] == 1 && $config['value'] > 0){
            $datas = [
                'link_id' => $order_id,
                'status' => 1,
                'title' => '评价赠送积分',
                'number' => $config['value'],
                'mark' => '评价赠送' . floatval($config['value']).'积分',
                'balance' => $data['integral'] + $config['value']
            ];
            $this->bill($data['uid'], 'integral', 'evaluate', 1, $datas);
        }
        $make = app()->make(UserRepository::class);
        $make->update($data['uid'], ['integral' => Db::raw('integral+' . $config['value'])]);
    }
    public function taskIntegral($groupOrder){

        if($groupOrder->activity_type == 1){
            $config = userIntegralConfig('buy_seckill_product');
            if($config['status'] == 1 && $config['value'] > 0){
                $total_num = app()->make(StoreOrderRepository::class)
                    ->search(['date'=>'today','uid'=>$groupOrder->uid,'activity_type'=>1])
                    ->where('paid', 1)
                    ->sum('total_num');

                $number = 0;
                if($total_num <= $config['num']){
                    $number =  $config['value'] * $groupOrder->total_num;
                }else{
                    $num = $total_num - $groupOrder->total_num;
                    if($num < $config['num']){
                        $number = ($config['num'] - $num) * $config['value'];
                    }
                }
                if($number > 0){
                    $data = [
                        'link_id' => $groupOrder['group_order_id'],
                        'status' => 1,
                        'title' => '购买秒杀商品赠送积分',
                        'number' => $number,
                        'mark' => '购买秒杀商品获赠' . floatval($number).'积分',
                        'balance' => $groupOrder->user->integral + $number
                    ];
                    $this->bill($groupOrder->uid, 'integral', 'buy_seckill_product', 1, $data);
                    $make = app()->make(UserRepository::class);
                    $make->update($groupOrder->uid, ['integral' => Db::raw('integral+' . $number)]);
                }

            }
        }else{
            $config = userIntegralConfig('buy_product');
            if($config['status'] == 1 && $groupOrder->pay_price > 0 && $config['value'] > 0){
                $countQuery = app()->make(StoreOrderRepository::class)->search(['date'=>'today','uid'=>$groupOrder->uid,'activity_type'=>0])->where('paid', 1);
                $countPay = $countQuery->sum('StoreOrder.pay_price');
                $number_total = 0;
                $number = 0;
                if($countPay >= $config['ask']){
                    if(($countPay - $groupOrder->pay_price) > $config['ask']){
                        $number = ceil($groupOrder->pay_price);
                    }else{
                        $number = ceil(($countPay - $config['ask'])) ?? 0;
                    }
                    $count = $this->getCount(['category' => 'integral','type' => 'buy_product','uid' => $groupOrder->uid]);
                    if($count < 1){
                        $number_total = $config['value'];
                        $data = [
                            'link_id' => 0,
                            'status' => 1,
                            'title' => '下单赠送积分',
                            'number' => $config['value'],
                            'mark' => '今日消费满' . floatval($config['ask']) . '元,赠送积分' . floatval($config['value']),
                            'balance' => $groupOrder->user->integral + $config['value']
                        ];
                        $this->bill($groupOrder->uid, 'integral', 'buy_product', 1, $data);
                        $groupOrder->user->integral  = $groupOrder->user->integral + $config['ask'];
                        sleep(1);
                    }
                }
                if($number >0){
                    $data = [
                        'link_id' => $groupOrder['group_order_id'],
                        'status' => 1,
                        'title' => '下单赠送积分',
                        'number' => $number,
                        'mark' => '今日消费已满' . floatval($config['ask']) . '元,额外赠送积分' . $number,
                        'balance' => $groupOrder->user->integral + $number
                    ];
                    $this->bill($groupOrder->uid, 'integral', 'buy_product', 1, $data);

                    $make = app()->make(UserRepository::class);
                    $make->update($groupOrder->uid, ['integral' => Db::raw('integral+' . ($number + $number_total))]);
                }
            }
        }


    }

    /**
     * 完善个人信息 + 绑定手机号 + 签到额外赠送积分
     * @param $userInfo
     * @param $key
     * @return void
     * @author: fupeng
     * @day: 2024/3/25
     */
    public function  userInfoIntegral($uid,$key){
        $config = userIntegralConfig($key);
        $user_info_time = systemConfig('user_info_time');
        $userInfo =  app()->make(UserRepository::class)->get($uid);
        if($config['status'] == 1 && $config['value'] > 0){

            switch ($key){
                case 'perfect_user_info':
                    $count = $this->getCount(['category' => 'integral','start_time'=>$user_info_time,'type' => $key,'uid' => $userInfo->uid]);
                    $title = '完善个人信息赠送积分';
                    $mark = '完善个人信息获赠'. floatval($config['value']) . '积分';
                    break;
                case 'bind_phone':
                    $count = $this->getCount(['category' => 'integral','type' => $key,'uid' => $userInfo->uid]);
                    $title = '绑定手机赠送积分';
                    $mark = '绑定手机号获赠'. floatval($config['value']) . '积分';
                    break;
                default :
                    $count = 0;
                    $title = '签到额外赠送积分';
                    $mark = '今日签到额外赠送'. floatval($config['value']) . '积分';
                    break;
            }
            if($count == 0){
                $data = [
                    'link_id' => 0,
                    'status' => 1,
                    'title' => $title,
                    'number' => $config['value'],
                    'mark' => $mark,
                    'balance' => $userInfo->integral + $config['value']
                ];
                $this->bill($userInfo->uid, 'integral', $key, 1, $data);
                $make = app()->make(UserRepository::class);
                $make->update($userInfo->uid, ['integral' => Db::raw('integral+' . ($config['value']))]);
            }
        }
    }



    public function  userKeyIntegral($uid,$config,$key){
           $userInfo =  app()->make(UserRepository::class)->get($uid);
            switch ($key){
                case 'browse_product':
                    $title = '浏览商品赠送积分';
                    $mark = '浏览商品获赠'. floatval($config['value']) . '积分';
                    break;
                case 'seckill_product':
                    $title = '浏览秒杀商品赠送积分';
                    $mark = '浏览秒杀商品获赠'. floatval($config['value']) . '积分';
                    break;
                case 'watch_video':
                    $title = '浏览视频赠送积分';
                    $mark = '浏览视频获赠'. floatval($config['value']) . '积分';
                    break;
                default :
                    $title = '观看广告赠送积分';
                    $mark = '观看广告获取'. floatval($config['value']) . '积分';
                    break;
            }
            $data = [
                'link_id' => 0,
                'status' => 1,
                'title' => $title,
                'number' => $config['value'],
                'mark' => $mark,
                'balance' => $userInfo->integral + $config['value']
            ];
            $this->bill($uid, 'integral', $key, 1, $data);
            $make = app()->make(UserRepository::class);
            $make->update($uid, ['integral' => Db::raw('integral+' . ($config['value']))]);
    }

    public function getCount($where)
    {
        return $this->dao->search($where)->count();
    }
}
